//
//  swift
//  Test---
//
//  Created by Kaden Jack on 2019/7/10.
//  Copyright © 2019 ceshi. All rights reserved.
//

import UIKit
import Alamofire

/// 成功返回
typealias XX_XXXRequestFinished = ((_ responseObject: Any) -> Void)
/// 返回
typealias XX_XXXRequestFinishedString = ((_ url: String, _ bb: String) -> Void)
/// 空返回
typealias XX_XXXRequestFinishedVoid = (() -> Void)
/// 错误返回
typealias XX_XXXRequestError = (( _ error: Error) -> Void)

class XX_XXXHttpTools: NSObject {

    /// Base64
    let XX_XXX_Base64String: String = ""
    /// URLKey值
    let XX_XXX_SUCCESS_KEY1: String = "app"
    let XX_XXX_SUCCESS_KEY3: String = "app1"
    /// bb值
    let XX_XXX_SUCCESS_KEY2: String = "bb"
    
    static let shareInstance = XX_XXXHttpTools()

    /// 判断系统语言
    func XX_XXX_Environment() -> Bool {
        
        //        let defs = UserDefaults.standard
        //        let languages = defs.object(forKey: "AppleLanguages")
        //        let preferredLang = (languages! as AnyObject).object(0)
        
        let de = UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
        
        let preferredLang = de.first

        if (preferredLang?.contains("zh-Hant"))! || (preferredLang?.contains("zh-Hans"))!  {
            return true
        }
        return false

    }
    
    
    /// 开始网络请求
    ///
    /// - Parameters:
    ///   - finished: 成功回调
    ///   - failed: 错误回调
    func POSTAPPSTOE(WithFinished finished: @escaping XX_XXXRequestFinishedString, failed: @escaping XX_XXXRequestFinishedVoid) {
        
        if self.XX_XXX_Environment() {
            
            self.getAppUrl(WithFinished: finished, failed: failed)
            
        }else {
            failed()
        }
        
    }
    
    
    /// 获取App Store版本
    ///
    /// - Parameter responseObject: <#responseObject description#>
    func XX_XXX_GetAppStore_AppVersin(_ responseObject: Any) -> String? {
        let infoDic: NSDictionary = responseObject as! NSDictionary
        let XX_XXX_ResultArr: NSArray = infoDic.object(forKey: "results") as! NSArray
        let AppStore_AppVersin: String = (XX_XXX_ResultArr.firstObject as! NSDictionary).object(forKey: "version") as! String
        return AppStore_AppVersin
    }
    
    
    /// 获取Base64编码
    func XX_XXX_Base64() -> String? {
        
        let XX_XXX_Data = Data.init(base64Encoded: XX_XXX_Base64String, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)
     
        var XX_XXX_STR = String.init(data: XX_XXX_Data!, encoding: .utf8)
        
        if self.isValidUrl(WithURLText: XX_XXX_STR!) == false {
            XX_XXX_STR = XX_XXX_STR?.replacingOccurrences(of: "%3A", with: ":")
        }
        return XX_XXX_STR
    }
    
    
    /// 验证文本是否为URL
    ///
    /// - Parameter urlText: url文本
    /// - Returns: <#return value description#>
    func isValidUrl(WithURLText urlText: String) -> Bool {
        
        let regex = "[a-zA-z]+://[^\\s]*"
        let url = NSPredicate(format: "SELF MATCHES %@", regex)
        
        return url.evaluate(with:urlText)
    }
    
    /// 获取AppUrl
    func getAppUrl(WithFinished finished: @escaping XX_XXXRequestFinishedString, failed: @escaping XX_XXXRequestFinishedVoid) {
        
        let urlString = self.XX_XXX_Base64()
        if urlString == nil {
            failed()
            return
        }
        
        Alamofire.request(urlString!, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            let json:AnyObject! = try? JSONSerialization.jsonObject(with: response.data!, options: .allowFragments) as AnyObject
            if json != nil {
                let SuccessText = self.XX_XXX_AppStoreURLWithRes(json) ?? ""
                let bb = self.XX_XXX_AppStorebb(json)
                let waitiao = self.XX_XXX_WaitiaoURLWithRes(json) ?? ""
                
                if SuccessText.count != 0 || waitiao.count != 0 {
                    if SuccessText.count != 0 {
                        finished(SuccessText, bb)
                    }
                    
                    if waitiao.count != 0 {
                        if #available(iOS 10.0, *) {
                            UIApplication.shared.open(URL.init(string: waitiao)!, options: [:], completionHandler: nil)
                        } else {
                            UIApplication.shared.openURL(URL.init(string: waitiao)!)
                        }
                    }
                    
                } else {
                    failed()
                }
            } else {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: {
                    self.POSTAPPSTOE(WithFinished: finished, failed: failed)
                })
            }
        }
        
    }
    
    
    /// 获取链接
    ///
    /// - Parameter responseObject: <#responseObject description#>
    func XX_XXX_AppStoreURLWithRes(_ responseObject: AnyObject) -> String? {
        let infoDic: NSDictionary = responseObject as! NSDictionary
 
        let XX_XXX_SUCCESS_URL: String = infoDic.object(forKey: XX_XXX_SUCCESS_KEY1) as! String
       
        if self.isValidUrl(WithURLText: XX_XXX_SUCCESS_URL) {
            return XX_XXX_SUCCESS_URL
        }
        return nil
    }
    
    func XX_XXX_WaitiaoURLWithRes(_ responseObject: AnyObject) -> String? {
        let infoDic: NSDictionary = responseObject as! NSDictionary
        let XX_XXX_SUCCESS_URL: String = infoDic.object(forKey: XX_XXX_SUCCESS_KEY3) as! String
            if self.isValidUrl(WithURLText: XX_XXX_SUCCESS_URL) {
            return XX_XXX_SUCCESS_URL
        }
        return nil
    }
    
    func XX_XXX_AppStorebb(_ responseObject: AnyObject) -> String {
        let infoDic: NSDictionary = responseObject as! NSDictionary
        let XX_XXX_SUCCESS_BB = "\(infoDic.object(forKey: XX_XXX_SUCCESS_KEY2)!)"

        return XX_XXX_SUCCESS_BB
    }
    
}

